package com.pinhuba.bams.view;

import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import com.pinhuba.bams.R;
import com.pinhuba.bams.framework.ErrorCode;
import com.pinhuba.bams.framework.UrlType;
import com.pinhuba.bams.framework.controller.Controller;
import com.pinhuba.bams.framework.controller.ErrorListener;
import com.pinhuba.bams.framework.Params;
import com.pinhuba.bams.framework.util.JsonHandle;
import com.pinhuba.bams.framework.util.Loger;
import com.pinhuba.bams.framework.util.PhoneStateUtil;
import com.pinhuba.bams.framework.util.SharePrefsHelper;
import com.pinhuba.bams.framework.util.ToastHelper;

public class LoginActivity extends Activity {
	private EditText username;
	private EditText passowrd;
	private CheckBox autoLogin;
	private CheckBox savePwd;
	private Button loginBtn;

	private ProgressDialog progressDialog;

	private SharePrefsHelper spHelper = null;
	private int errorCode;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		initView();
		initData();
		setListener();

		if (judgeEnvironment()) {
			if (judgeAutoLogin()) {
				Controller.getInstance().doRequest(LoginActivity.this, UrlType.LOGINCHECK, loginListener,
						Params.login(spHelper.getLastestUserLoginAccount(), spHelper.getLastestUserLoginPwd()));
				progressDialog.show();
			}
		}
	}

	private boolean judgeEnvironment() {
		if (!PhoneStateUtil.exterStorageReady()) {
			errorCode = 1;
		} else if (PhoneStateUtil.isAirplaneModeOn(getApplicationContext()) || !PhoneStateUtil.hasInternet()) {
			errorCode = 2;
		} else {
			errorCode = 0;
		}
		if (errorCode == 0) {
			return true;
		} else {
			ToastHelper.showShortMsg(errorCode == 1 ? R.string.no_sd : R.string.please_open_network);
			return false;
		}
	}

	private boolean judgeAutoLogin() {
		return spHelper.getIfAutoLogin();
	}

	private void initView() {
		username = (EditText) findViewById(R.id.username);
		passowrd = (EditText) findViewById(R.id.passowrd);
		autoLogin = (CheckBox) findViewById(R.id.auto_login);
		savePwd = (CheckBox) findViewById(R.id.save_pwd);
		loginBtn = (Button) findViewById(R.id.login_bt);

		progressDialog = new ProgressDialog(LoginActivity.this);
		progressDialog.setMessage(getResources().getString(R.string.login_now));
		progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progressDialog.setCancelable(false);
	}

	private void initData() {
		spHelper = new SharePrefsHelper(getApplicationContext());
		if (spHelper.getLastestUserLoginAccount() != null) {
			username.setText(spHelper.getLastestUserLoginAccount());
		}
		if (spHelper.getIfSavePwd() && spHelper.getLastestUserLoginPwd() != null) {
			passowrd.setText(spHelper.getLastestUserLoginPwd());
		}
	}

	private void setListener() {

		savePwd.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if (!isChecked && autoLogin.isChecked()) {

				}
			}
		});

		autoLogin.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if (isChecked && !savePwd.isChecked()) {

				}
			}
		});

		loginBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String name = username.getText().toString().trim();
				String pwd = passowrd.getText().toString().trim();
				if (name.equals("")) {
					ToastHelper.showShortMsg(R.string.name_can_not_empty);
				} else {
					Controller.getInstance().doRequest(LoginActivity.this, UrlType.LOGINCHECK, loginListener, Params.login(name, pwd));
					progressDialog.show();
				}
			}
		});
	}

	private ErrorListener loginListener = new ErrorListener() {

		@Override
		public void onSuccess(UrlType type, String json) {
			Loger.d("The json is" + json);
			if (progressDialog.isShowing())
				progressDialog.dismiss();
			try {
				JSONObject loginJson = new JSONObject(json);
				if (JsonHandle.getInstance().jsonCodeHandle(loginJson) == 0) {
					String sessionId = loginJson.getString("sessionId").trim();
					String name = loginJson.getString("name").trim();
					spHelper.setIfSavePwd(savePwd.isChecked());
					spHelper.setIfAutoLogin(autoLogin.isChecked());
					if (savePwd.isChecked()) {
						spHelper.setLastestLoginPwd(passowrd.getText().toString().trim());
					}
					Params.setUserSessionId(sessionId);
					spHelper.setLastestUserLoginAccount(username.getText().toString().trim());
					spHelper.setLastestUserName(name);
					ToastHelper.showShortMsg(getResources().getString(R.string.welcome_user) + name);
					Intent it = new Intent(LoginActivity.this, MainActivity.class);
					startActivity(it);
					LoginActivity.this.finish();
				}
			} catch (JSONException e) {

			} finally {

			}
		}

		@Override
		public void onError(UrlType type, ErrorCode code) {
			Loger.d("The onError is" + code.name());
			progressDialog.dismiss();
			switch (code) {
			case READW_TIMOUT:
				ToastHelper.showShortMsg(R.string.exception_readw_timeout);
				break;
			case AIRPLANE_MODE:
				ToastHelper.showShortMsg(R.string.exception_airplane_mode);
				break;
			case NO_INTERNET:
				ToastHelper.showShortMsg(R.string.exception_no_internet);
				break;
			case INVALID_IO:
				ToastHelper.showShortMsg(R.string.exception_invaild_io);
				break;
			default:
				break;
			}
		}
	};
}
